package com.k.kpp.config.http;

import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
import org.apache.hc.core5.ssl.SSLContextBuilder;
import org.apache.hc.core5.ssl.TrustStrategy;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * @author k
 */
public class HttpClientConfig {
    @Bean
    @ConfigurationProperties("http.client")
    public HttpClientProperties getHttpClientProperties(){
        return new HttpClientProperties();
    }
    @Bean
    @ConfigurationProperties("http.pool")
    public HttpPoolProperties getFtpPoolProperties(){
        return new HttpPoolProperties();
    }

    @Bean
    public SSLContextBuilder ssLContextBuilder() throws KeyStoreException, NoSuchAlgorithmException {
        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        // 全部信任 不做身份鉴定
        sslContextBuilder.loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        });
        return sslContextBuilder;
    }

    @Bean
    public SSLConnectionSocketFactory sslSocketFactory(SSLContextBuilder sslContextBuilder) throws KeyManagementException, NoSuchAlgorithmException {
        return new SSLConnectionSocketFactory(sslContextBuilder.build(),
                new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"},
                null,
                NoopHostnameVerifier.INSTANCE);
    }

    @Bean
    public HttpClientFactory getFtpClientFactory(HttpClientProperties ftpClientProperties){
        return new HttpClientFactory(ftpClientProperties);
    }

    @Bean
    public HttpClientTemplate getFtpClientTemplate(HttpClientFactory httpClientFactory,HttpPoolProperties httpPoolProperties){
        return new HttpClientTemplate(httpClientFactory,httpPoolProperties);
    }
}
